package com.car.action.api;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.car.action.util.CommonController;
import com.car.common.model.BlackList;
import com.car.common.model.Message;
import com.car.common.model.MessageUnreadNum;
import com.car.common.model.Prop;
import com.car.common.model.PropRecord;
import com.car.common.model.Resume;
import com.car.common.model.UserBlack;
import com.car.common.model.UserFans;
import com.car.common.model.UserFriends;
import com.car.common.model.UserHellos;
import com.car.common.model.UserWatch;
import com.car.common.model.Users;
import com.car.job.TheadImgCheck;
import com.car.tx.UserService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.utils.APIJSON;
import com.utils.DateUtil;
import com.utils.PicUtil;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;

public class FriendController extends CommonController {
	
	private static Logger logger = Logger.getLogger(FriendController.class);
	
	public void search_friend() {
		String name = getPara("name");
		List<Users> userList = Users.dao.find("select id from users where id = '" + name+ "' or nick_name ='" + name +"' order by id desc limit 8 ");
		List<Map<String, Object>> result = Lists.newArrayList();
		for(Users one : userList) {
			String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
			sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + one.getId();
			Users users = Users.dao.findFirst(sql);
			result.add(Users.dao.info(users,null));
		}
		renderText(APIJSON.send(result));
	}
	
    /**
     * 获取获我的好友
     */
	public void get_list() {
	  	String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FRIEND, user_id.intValue());
			String andSQL = "  (user_id = "+ user_id +" or target_user_id = " + user_id +") and status = 1 and delete_time is null order by id desc ";
			List<UserFriends> friends = UserFriends.dao.find("select * from user_friends where " + andSQL);
			ArrayList<Map<String,Object>> result = Lists.newArrayList();
			for(UserFriends one : friends) {
				int userid = one.getUserId();
				int target_userid = one.getTargetUserId();
				int uid = userid;
				if (user_id.intValue() == userid) {
					uid = target_userid;
				}
				
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + uid;
				
				Users users = Users.dao.findFirst(sql);
				result.add(Users.dao.info(users,null));
			}
			renderText(APIJSON.send(result));
		}
	}
	
    /**
     * 判断是否是好友
     */
	public void is_friend() {
	  	String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Map<String,Object> result = Maps.newLinkedHashMap();
			Long user_id = super.getUserId();
			int target_user_id = getParaToInt("target_user_id");
			 //判断是否是好友
			UserFriends friend = UserFriends.dao.findFirst("select id from user_friends where (user_id = "+ user_id +" and target_user_id = " + target_user_id +")  or "+ " (user_id = "+ target_user_id +" and target_user_id = " + user_id +") and status = 1 and delete_time is null order by id desc limit 1 ");
			result.put("is_friend", friend != null ? 1 :2);
			//判断是否关注
			UserFans fan = UserFans.dao.findFirst("select id , user_id from user_fans where (user_id = " + user_id+ " and target_user_id = " + target_user_id +") and delete_time is null ");
			result.put("is_follow", fan != null ? 1 :2);
			if (fan != null) {
				if (fan.getUserId() == 141 || fan.getUserId() == 200) {
					result.put("is_follow", 1);
				}
			}
			UserBlack black = UserBlack.dao.findFirst("select id from user_black where status = 1 and user_id = " + user_id +" and black_user_id = " + target_user_id );
			result.put("is_black", black != null ? 1 :2);
			
			RongCloudUtil.sendTxt(String.valueOf(user_id), String.valueOf(target_user_id), "我们已经是好友了，快来聊天吧");
			renderText(APIJSON.send(result));
		}
	}
	
	 /**
     * 认证女号 可以直接  加好友
     */
	public void add() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			int target_user_id = getParaToInt("target_user_id");
			 //判断是否是好友
			UserFriends one = UserFriends.dao.findFirst("select id from user_friends where (user_id = "+ user_id +" and target_user_id = " + target_user_id +") and status = 1 and delete_time is null order by id desc limit 1 ");
			if(one == null) {
				one = new UserFriends();
				one.setUserId(user_id.intValue());
				one.setTargetUserId(target_user_id);
				one.setStatus(1);
				one.setCreateTime(SystemClock.now()/1000L);
				one.setUpdateTime(SystemClock.now()/1000L);
				if (one.save()) {
					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FRIEND, target_user_id);
					RongCloudUtil.sendTxt(String.valueOf(user_id), String.valueOf(target_user_id), "我们已是好友了!");
					RongCloudUtil.sendTxt(String.valueOf(target_user_id), String.valueOf(user_id), "我们已是好友了!");
				}
			}
			renderText(APIJSON.result(0));
		}
	}
	
	
	/**
     * 删除好友
     */
	public void remove() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			int target_user_id = getParaToInt("target_user_id");
			Db.delete("delete from user_friends where (user_id = "+ user_id +" and target_user_id = " + target_user_id +") and status = 1 ");
			renderText(APIJSON.result(0));
		}
	}
	
	/**
	 *   打招呼
	 */
	public void hello(){
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			String content =  getPara("content");
			if (StringUtil.empty(content)) {
				renderText(APIJSON.result(2001));
				return;
			}
			//含有违法关键词
			if (BlackList.dao.check_content(content)) {
				renderText(APIJSON.result(2007));
				return;
			}
			if (StringUtil.empty(getPara("target_user_id"))) {
				renderText(APIJSON.result(4000));
				return;
			}
			Long user_id = super.getUserId();
			int target_user_id = getParaToInt("target_user_id");
			if (user_id.intValue() == target_user_id ){
				renderText(APIJSON.result(1032));
				return;
			}
			boolean blackFlg = UserBlack.dao.is_black(target_user_id,user_id.intValue());
			if(blackFlg){
				renderText(APIJSON.result(1068));
				return;
			}
			UserFriends friend = UserFriends.dao.findFirst("select id from user_friends where (user_id = "+ user_id +" and target_user_id = " + target_user_id +")  or "+ " (user_id = "+ target_user_id +" and target_user_id = " + user_id +") and status = 1 and delete_time is null order by id desc limit 1 ");
			if(friend != null){
				renderText(APIJSON.result(1031));
				return;
			}
			// 
			String hello_sql  = "select id from user_hellos where (user_id = "+user_id+" and target_user_id = " + target_user_id + " and status = 2) and delete_time is null order by id desc limit 1";
			String tohello_sql  = "select id from user_hellos where (target_user_id = "+user_id+" and user_id = " + target_user_id + " and status = 2) and delete_time is null order by id desc limit 1";
			UserHellos hello =  UserHellos.dao.findFirst(hello_sql);
			UserHellos tohello =  UserHellos.dao.findFirst(tohello_sql);
			if (hello != null){
				renderText(APIJSON.result(1056));
				return;
			} else if (tohello != null){
				renderText(APIJSON.result(1057));
				return;
			} else {
				hello = new UserHellos();
				hello.setUserId(user_id.intValue());
				hello.setTargetUserId(target_user_id);
				hello.setContent(content);
				hello.setStatus(2);
				hello.setTodayTime(SystemClock.now()/1000);
				hello.setCreateTime(SystemClock.now()/1000);
				hello.setUpdateTime(SystemClock.now()/1000);
				if (hello.save()){
					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FRIEND, target_user_id);
					// TODO 消息推送
				}
				renderText(APIJSON.result(0));
				return;
			} 
		}
	}
	

	/**
	 * 获取打招呼列表
	 */
	public void hello_list() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			int page = 1;
	        if(!StringUtil.empty(getPara("page"))) {
	        	page = getParaToInt("page");
	        }
	        Long user_id = super.getUserId();
	        List<UserHellos> friendList = UserHellos.dao.find("select * from user_hellos where (user_id = "+ user_id +" or target_user_id = " + user_id +")   and status = 2 and delete_time is null order by id desc limit " + (page - 1) * 15 +",15");
	        MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FRIEND, user_id.intValue());
	        List<Map<String,Object>> result = Lists.newArrayList();
	        for(UserHellos one : friendList) {
	        	Map<String,Object> map = Maps.newHashMap();
	        	int show_user_id = 0;
	        	if (user_id.intValue() == one.getUserId()) {
	        		map.put("type", 1);
	        		show_user_id = one.getTargetUserId();
	        	} else {
	        		map.put("type", 2);
	        		show_user_id = one.getUserId();
	        	}
	        	map.put("status", one.getStatus());
	        	map.put("time", DateUtil.cul(one.getCreateTime()));
	        	map.put("content", StringUtil.decode(one.getContent()));
	        	map.put("hello_id", one.getId());
	        	String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit from users as u left join area ae on ae.code = u.area_id where u.id = " + show_user_id;
				
				Users user = Users.dao.findFirst(sql);
				map.put("user_data",  Users.dao.info(user,null));
				result.add(map);
	        }
	        renderText(APIJSON.send(result));
		}
	}
	
	/**
     * 处理好友申请
     */
    public void handle() {
    	String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			if (StringUtil.empty(getPara("hello_id"))) {
				renderText(APIJSON.result(4000));
				return;
			}
			if (StringUtil.empty(getPara("status"))) {
				renderText(APIJSON.result(4000));
				return;
			}
			int status = getParaToInt("status");
			int id = getParaToInt("hello_id");
			Db.update("update user_hellos set status = " + status + " where id = " + id );
			// 同意 -1拒绝 1同意
			if (status == 1) {
				// 计算好友数量
				UserHellos oneHello = UserHellos.dao.findById(id);
				int user_id = oneHello.getUserId();
				
				int target_user_id = oneHello.getTargetUserId();
				UserFriends countFriends = UserFriends.dao.findFirst("select count(id) as cnt from user_friends where (user_id = "+ user_id + " and target_user_id = " + target_user_id +")  or (user_id = "+ target_user_id + " and target_user_id = " + user_id +") and status = 1 and delete_time is null ");
				if (countFriends != null) {
					int count = Integer.valueOf(String.valueOf(countFriends.get("cnt")));
					Users users = Users.dao.findById(user_id);
					int vip = users.getInt("vip_badpe");
					if (vip == 0 && count > 10) {
						renderText(APIJSON.result(6010));
						return;	
					} else {
						if (count > (20 + vip*10) ) {
							renderText(APIJSON.result(6010));
							return;	
						}
					}
				}
				UserFriends one = UserFriends.dao.findFirst("select id from user_friends where (user_id = "+ user_id +" and target_user_id = " + target_user_id +")  or "+ " (user_id = "+ target_user_id +" and target_user_id = " + user_id +") and status = 1 and delete_time is null order by id desc limit 1 ");
				if (one == null) {
					one = new UserFriends();
					one.setUserId(user_id);
					one.setTargetUserId(target_user_id);
					one.setStatus(1);
					one.setCreateTime(SystemClock.now()/1000L);
					one.setUpdateTime(SystemClock.now()/1000L);
					one.save();
				} else {
					Db.update("update user_friends set status = " + 1 +" where id = " + one.getId());
				}
				// 推送 
				Map<String, String> params = Maps.newHashMap();
				params.put("userId",   		String.valueOf(user_id));
				params.put("blackUserId",   String.valueOf(target_user_id));
				RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
				
				params.put("userId",   		String.valueOf(target_user_id));
				params.put("blackUserId",   String.valueOf(user_id));
				RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
				// /user/blacklist/remove.json
			}
			renderText(APIJSON.result(0));
		}
    }
    
	/**
	 * 礼物列表
	 */
	public void gift_list() {
		int type = 0;
		if (!StringUtil.empty(getPara("type"))) {
			type = getParaToInt("type");
		}
		List<Prop> propList = null;
		if(type == 0) {
			propList = Prop.dao.find("select id,name,icon,hot_val from prop where status = 1 and type = " + type  +" order by sort desc , hot_val asc ");
		} else {
			Long user_id = super.getUserId();
			propList = Prop.dao.find("select p.id,p.name,p.icon,p.hot_val from prop as p left join prop_record as r on r.prop_id = p.id where p.type = 1 and r.user_id =" + user_id);
		}
		List<Map<String,Object>> result = Lists.newArrayList();
		for(Prop one : propList) {
			Map<String,Object> temp = Maps.newHashMap();
			temp.put("id", 		one.get("id"));
			temp.put("name", 	one.get("name"));
			temp.put("img", 	PicUtil.QINIU_DIR + one.get("icon"));
			temp.put("hot_val", one.get("hot_val"));
			result.add(temp);
		}
		renderText(APIJSON.send(result));
	}
	
	/**
	 * 收到的礼物
	 */
	public void rec_gift_list() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			
		    int page = 1;
	        if(!StringUtil.empty(getPara("page"))) {
	    	   page = getParaToInt("page");
	        }
			Long user_id = super.getUserId();
			MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_GIFT, user_id.intValue());
			List<Prop> propList = Prop.dao.find("select p.id,p.name,p.icon,p.hot_val,r.user_id,r.nick_name,r.user_header,r.createtime,r.num from prop as p left join prop_record as r on r.prop_id = p.id where r.target_user_id = " + user_id  +" order by r.createtime desc limit " + (page -1) * 15 +",15" );
			List<Map<String,Object>> result = Lists.newArrayList();
			for(Prop one : propList) {
				Map<String,Object> temp = Maps.newHashMap();
				temp.put("id", 			one.get("id"));
				temp.put("name", 		one.get("name"));
				temp.put("img", 		PicUtil.QINIU_DIR + one.get("icon"));
				temp.put("hot_val",   	one.get("hot_val"));
				temp.put("user_id",   	one.get("user_id"));
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit from users as u left join area ae on ae.code = u.area_id where u.id = " + one.get("user_id");
				Users user = Users.dao.findFirst(sql);
				temp.put("user_data",   Users.dao.info(user,null));
				temp.put("nick_name", 	one.get("nick_name"));
				temp.put("user_header", PicUtil.QINIU_DIR + one.get("user_header"));
				temp.put("create_time", one.get("createtime"));
				temp.put("num", 		one.get("num"));
				result.add(temp);
			}
			renderText(APIJSON.send(result));
		}
	}
	
	/**
	 * 送礼物
	 * HttpKit.readData(getRequest())
	 */
	public void send_gift() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Prop prop = Prop.dao.findById(getPara("prop_id"));
			if (prop == null) {
				renderText(APIJSON.result(6001));
				return ;
			}
			int target_user_id = getParaToInt("target_user_id");
			Long user_id = super.getUserId();
			Users users = Users.dao.findById(user_id);
			
		    int num = 1;
	        if(!StringUtil.empty(getPara("num"))) {
	        	num = getParaToInt("num");
	        }
			int type = prop.getType();
			if (type == 0) {
				Long hotVal = users.getHotVal();
				if (hotVal.intValue() <= prop.getHotVal() * num) {
					renderText(APIJSON.result(2003));
					return;
				} else {
					try {
						int times = UserService.one.send_gift(user_id,target_user_id,prop,num);
						Map<String,Object> result = Maps.newHashMap();
						result.put("times", times);
						// TODO推送消息
						MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_GIFT, target_user_id);
						renderText(APIJSON.send(result));
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage());
						renderText(APIJSON.result(4000));
					}
					
				}
			} else {
				PropRecord record = PropRecord.dao.findFirst("select id from prop_record where prop_id = " + prop.getId() +" and user_id = " + user_id + " and target_user_id = 0 order by id asc limit 1 " );
				if (record != null) {
					Db.update("update prop_record set target_user_id = " + target_user_id + " where id = "+ record.getId());
					Db.update("update users set credit = credit + 1 where id = "+ target_user_id);
					
					Map<String,Object> result = Maps.newHashMap();
					result.put("times", 0);
					renderText(APIJSON.send(result));
				} else {
					renderText(APIJSON.result(1070));
					return ;
				}
				
				
			}
		}
	}
	
	
	/**
	 * 发出的告白书
	 */
	public void send_express_list() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			List<Resume> resumeList = Resume.dao.find("select distinct target_user_id from resume as r where r.user_id = " + user_id + " order by r.id desc");
			List<Map<String,Object>> result = Lists.newArrayList();
			for(Resume one : resumeList) {
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit from users as u left join area ae on ae.code = u.area_id where u.id = " + one.getTargetUserId();
				Users user = Users.dao.findFirst(sql);
				result.add(Users.dao.info(user,null));
			}
			renderText(APIJSON.send(result));
		}
	}
	
	
	/**
	 * 历史收到的告白书
	 * @param status 1 看过 2 不感兴趣
	 */
	public void rec_express_history() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			int credit = 0 ;
			if (!StringUtil.empty(getPara("credit"))){
				credit = getParaToInt("credit");
			}
			int status = 0 ;
			if (!StringUtil.empty(getPara("status"))){
				status = getParaToInt("status");
			}
			List<Resume> resumeList = Resume.dao.find("select r.* from resume as r left join users as u on u.id = r.user_id  where u.credit >= "+ credit +" and r.target_user_id = " + user_id + " and  r.expiretime < " + (SystemClock.now()/1000L -1*24*3600L) + " and r.status = "+ status +" order by r.id desc");
			List<Map<String,Object>> result = Lists.newArrayList();
			for(Resume one : resumeList) {
				Map<String,Object> map = Maps.newHashMap();
				map.put("id", one.get("id"));
				map.put("user_id", one.getUserId());
				map.put("nick_name", one.getNickName());
				String user_head = one.getUserHeader();
				String[] headArray = user_head.split(",");
				List<String> head = Lists.newArrayList();
				for(String str : headArray) {
					head.add(PicUtil.QINIU_DIR + str);
				}
				map.put("user_head", head);
				map.put("weight", one.getWeight());
				map.put("height", one.getHeight());
				
				map.put("edu", one.get("edu"));
				map.put("income", one.get("income"));
				map.put("position", one.getPosition());
				
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit from users as u left join area ae on ae.code = u.area_id where u.id = " + one.getUserId();
				Users user = Users.dao.findFirst(sql);
				map.put("user_data",   Users.dao.info(user,null));
				result.add(map);
			}
			
			renderText(APIJSON.send(result));
		}
	}
	
	/**
	 * 收到的告白书
	 */
	public void rec_express_list() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			int credit = 0 ;
			if (!StringUtil.empty(getPara("credit"))){
				credit = getParaToInt("credit");
			}
			List<Resume> resumeList = Resume.dao.find("select r.* from resume as r left join users as u on u.id = r.user_id  where u.credit >= "+ credit +" and r.target_user_id = " + user_id + " and  r.expiretime > " + SystemClock.now()/1000L + " and r.status = 0 order by r.id desc");
			List<Map<String,Object>> result = Lists.newArrayList();
			for(Resume one : resumeList) {
				Map<String,Object> map = Maps.newHashMap();
				map.put("id", one.get("id"));
				map.put("user_id", one.getUserId());
				map.put("nick_name", one.getNickName());
				String user_head = one.getUserHeader();
				String[] headArray = user_head.split(",");
				List<String> head = Lists.newArrayList();
				for(String str : headArray) {
					head.add(PicUtil.QINIU_DIR + str);
				}
				map.put("user_head", head);
				map.put("weight", one.getWeight());
				map.put("height", one.getHeight());
				
				map.put("edu", one.get("edu"));
				map.put("income", one.get("income"));
				map.put("position", one.getPosition());
				
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit from users as u left join area ae on ae.code = u.area_id where u.id = " + one.getUserId();
				Users user = Users.dao.findFirst(sql);
				map.put("user_data",   Users.dao.info(user,null));
				result.add(map);
			}
			
			MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_EXPRESS, user_id.intValue());
			renderText(APIJSON.send(result));
		}
	}
	
	
	/**
	 * 发送告白书
	 */
	public void refuse_express() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			if (StringUtil.empty(getPara("id"))) {
				renderText(APIJSON.result(4000));
				return;
			}
			Db.update("update resume set status = -1 where id = " + getPara("id"));
			renderText(APIJSON.result(0));
		}	
	}
	
	/**
	 * 免费次数 
	 */
	public void express_free_cnt() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Users users = Users.dao.findById(user_id);
			// TODO 每天投递次数限制
			int times = 1 ;
			int vip_badpe = users.getInt("vip_badpe");
			if (users.getVipEndTime() < SystemClock.now()/1000) {
				
			} else {
				if (vip_badpe == 1) {
					times = 30;
				} else if (vip_badpe == 2) {
					times = 50;
				} else if (vip_badpe == 3) {
					times = 100;
				}
			}
			Calendar  cal = Calendar.getInstance();
			cal.setTimeInMillis(SystemClock.now());
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			long starttime = cal.getTimeInMillis() /1000L;
			cal.add(Calendar.DAY_OF_MONTH, 1);
			long endtime = cal.getTimeInMillis() /1000L;
			Resume cntResume = Resume.dao.findFirst("select count(id) as cnt from resume where user_id = " + user_id +" and createtime > " + starttime +" and createtime < " + endtime);
			int cnt = Integer.valueOf(cntResume.getStr("cnt"));
			Map<String, Object> data = Maps.newHashMap();
			if (times <= cnt) {
				data.put("free_times", 0);
				data.put("tip", "开通vip可增加每天免费30次数或发送告白书是需要1000热度");
				renderText(APIJSON.send(data));
				return; 
			} else {
				data.put("free_times", times - cnt);
				data.put("tip", "开通vip可增加每天免费30次数或发送告白书是需要1000热度");
				renderText(APIJSON.send(data));
				return;
			}
		}
	}
	
	/**
	 * 发送告白书
	 */
	public void send_express() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			String user_header = getPara("user_header");
			String weight  = getPara("weight");
			String height  = getPara("height");
			String position  = getPara("position");
			String edu  = getPara("edu");
			String income  = getPara("income");
			// StringUtil.empty(user_header) ||
			if ( StringUtil.empty(weight) || StringUtil.empty(height) || StringUtil.empty(edu) || StringUtil.empty(income)) {
				renderText(APIJSON.result(4001));
				return;
			}
			int target_user_id = getParaToInt("target_user_id");
			Long user_id = super.getUserId();
			Users users = Users.dao.findById(user_id);
			/*
			if(StringUtil.empty(users.getUserMobile())) {
				renderJson(APIJSON.result(3019));
				return;
			}
			*/
			int times = 10 ;
			int vip_badpe = users.getInt("vip_badpe");
			if (users.getVipEndTime() < SystemClock.now()/1000) {
				
			} else {
				if (vip_badpe == 1) {
					times = 30;
				} else if (vip_badpe == 2) {
					times = 50;
				} else if (vip_badpe == 3) {
					times = 100;
				}
			}
			Calendar  cal = Calendar.getInstance();
			cal.setTimeInMillis(SystemClock.now());
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			long starttime = cal.getTimeInMillis() /1000L;
			cal.add(Calendar.DAY_OF_MONTH, 1);
			long endtime = cal.getTimeInMillis() /1000L;
			Resume cntResume = Resume.dao.findFirst("select count(id) as cnt from resume where user_id = " + user_id +" and createtime > " + starttime +" and createtime < " + endtime);
			int cnt = Integer.valueOf(cntResume.getStr("cnt"));
			if (times <= cnt) {
				if (users.getHotVal().intValue() < 1000L) {
					renderText(APIJSON.result(1082));
					return;
				} else {
					Db.update("update users set hot_val = hot_val - 1000 where id = " + user_id);
				}
			}
			Resume one = new Resume();
			one.setNickName(StringUtil.decode(users.getNickName()));
			one.setUserId(user_id.intValue());
			one.setUserHeader(user_header);
			one.setTargetUserId(target_user_id);
			one.setWeight(weight);
			one.setHeight(height);
			one.setPosition(position);
			one.set("edu", edu);
			one.set("income", income);
			one.setStatus(0);
			one.setCreatetime(SystemClock.now()/1000L);
			one.setExpiretime(SystemClock.now()/1000L + 30*24*3600L);
			if (one.save()) {
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_EXPRESS, target_user_id);
				String [] arr_images = user_header.split(","); 
				Map<String,Object> handleData = Maps.newHashMap(); 
				handleData.put("relation_id", one.getId());
				handleData.put("img", arr_images);
				handleData.put("type", 10);
				new Thread(new TheadImgCheck(handleData)).start();
				
			}
			renderText(APIJSON.result(0));
		}
	}

	/**
	 * 守护
	 */
	public void guard() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			int target_user_id = getParaToInt("target_user_id");
			UserWatch  one = UserWatch.dao.findFirst("select * from user_watch  where user_id = " + user_id +" and target_user_id = " + target_user_id);
			if (one == null ) {
				Users users = Users.dao.findById(user_id);
				Long hotVal = users.getHotVal();
				if (hotVal < 30000L) {
					renderText(APIJSON.result(2003));
					return;
				} else {
					one = new UserWatch();
					one.setUserId(user_id.intValue());
					one.setTargetUserId(target_user_id);
					one.set("nick_name",  StringUtil.decode(users.getNickName()));
					one.set("user_header", users.getUserHeader());
					one.set("hot_val", 30000);
					one.setCreateTime(SystemClock.now()/1000L);
					one.save();
					Db.update("update users set hot_val = hot_val - 30000 , credit = credit + 1 where id = " + user_id);
					Db.update("update users set free_hot = free_hot + 15000 , credit = credit + 1 where id = " + target_user_id);
				}
			}
			renderText(APIJSON.result(0));
		}
	}
}
